import { Button, Col, Divider, Drawer, Form, message, Modal, Row, List,Badge,Timeline,Avatar  } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import moment from "moment";
import React from "react";
import TimeLineRecords from "./timeLineRecords";
import WorkOrderInfo from "./workOrderInfo";
import { workOrderClose, workOrderDetail, workOrderTimeLine } from "@/services/workOrder";
import AllocateModal from "./allocateModal";
import ReplayModal from "./replayModal";
import DealtwithTime from "./dealtwithTime";
import ExtraFields from "./extraFields";
import TimeList from "./timeList";
import ReactMarkdown from 'react-markdown';
import {exportSessionDetail, getSessionContext} from "@/services/datastatistics";

class ProcessingDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      detail:null,
      id:null,
      readonly:true,
      allocatedDisabled:true,
      replayDisabled:true,
      orderProcessList:[],
      solutionDuration:0.5,
      ticketChatHistoryDetail:[],
      chatModelVisible:false,
      durationAdjustReason: ""
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }

  }

  /**
   * 
   * @param {*} id 工单id
   * @param {*} readonly 是否只读 true只读
   * @param {*} allocatedDisabled 是否禁用分配按钮 true禁用
   * @param {*} replayDisabled 是否禁用回复按钮 true禁用
   */
  initData = (id,readonly,allocatedDisabled,replayDisabled) => {
    this.setState({
      visible:true,
      id,
      readonly,
      allocatedDisabled,
      replayDisabled,
    },() => {
      this.getOrderInfo(id)
      this.getTimeLine(id)
    })
  }

  getOrderInfo = async (id) => {
    const res = await workOrderDetail({id})
    this.setState({detail:res})
    if(res.ticketStatus == 4){
      this.setState({readonly:true})
    }
  }

  showChatModal = async () => {
    this.setState({
      chatModelVisible: true,
    });
    try {
      const ticketDetail = this.state.detail;
      if (ticketDetail != null && ticketDetail.chatDetail != null){
        let detailJson = JSON.parse(ticketDetail.chatDetail)
        if ('statChatIds' in detailJson){
          let params = {applicationId:ticketDetail.applicationId,sessionId:detailJson.sessionId,statChatIds:(detailJson.statChatIds || []).join(',')};
          let session = await exportSessionDetail(params)
          if (session.length > 0){
            this.setState({ticketChatHistoryDetail:session})
          }else {
            this.setState({ticketChatHistoryDetail:[]})
          }
        }
      }
    }catch (err){
      this.setState({ticketChatHistoryDetail:[]})
    }
  };

  handleChatModelCancel = e => {
    this.setState({
      chatModelVisible: false,
    });
  };

  getTimeLine = async id => {
    const res = await workOrderTimeLine({ticketId:id})
    this.setState({orderProcessList:res})
  }

  cancelModal = () => {
    this.setState({
      visible:false,
      detail:null,
      id:null,
      readonly:true,
      allocatedDisabled:true,
      replayDisabled:true,
      ticketChatHistoryDetail:[],
      chatModelVisible:false,
    })
    if(this.props.refreshUnReadNum){
      this.props.refreshUnReadNum()
    }
  }

  openAllocateModal = () => {
    this.AllocateModal.initData(this.state.id)
  }

  openReplayModal = () => {
    this.ReplayModal.initData(this.state.id)
  }

  //回复或者指派 成功后的回调
  operationCallback = () => {
    this.cancelModal()
    if(this.props.refreshList){
      this.props.refreshList()
    }
  }

  baseFormEditTrue = () => {
    this.WorkOrderInfo.changeInfo()
  }

  updateInfo = () => {
    this.getOrderInfo(this.state.id)
    this.getTimeLine(this.state.id)
  }

  /**
   * 
   * @param {*} data 
   * @param {*} type 
   */
  doDealtwithTime = (type,values) => {
    this.DealtwithTime.initModal(type,values)
  }

  getSolutionDuration = (solutionDuration,states) => {
    const {type,params} = states
    params.solutionDuration = solutionDuration
    if(type == 'workOrderInfo'){
      this.WorkOrderInfo.doUpdate(params)
    }
    if(type == 'close'){
      this.closeOrder(params)
    }
    
  }

  openExtraModal = type => {
    this.ExtraFields.initModal({type,ticketId:this.state.detail.id,visible:true})
  }

  closeOrder = async params => {
    const res = await workOrderClose({solutionDuration:params.solutionDuration,id:this.state.detail.id})
    message.info(res.message)
    this.updateInfo()
  }

  openModal = () => {
    this.TimeList.init(this.state.detail.id)
  }
  
  render(){
    const { visible,detail,readonly,allocatedDisabled,replayDisabled,orderProcessList,solutionDuration } = this.state;
    const renderFileUrl = (item) => {
      let html =
        '<p style="margin: 0px;word-break: break-word;"><a style="color: #11CBFF;" href="' +
        config.fileUrl +
        "cloud/file/download/" +
        item.fileId +
        '">' +
        item.fileName +
        "</a></p>";
      return html;
    };
    const boxStyle = {
      display:"flex",
      alignItems:"flex-start",
      marginBottom:20    
    }
    const labelStyle = {
      width:80,
      flexShrink:0,
      textAlign:'right',
      color:"rgba(0, 0, 0, 0.85)"
    }
    return (
      <Drawer
        visible={visible}
        title={formatMessage({id: 'pages.workOrder.processing.detail.title'})}
        onClose={this.cancelModal}
        width='100%'
        bodyStyle={{height:"calc(100vh - 60px)",overflowY:"auto"}}
      >
        {
          detail ? (
            <div style={{display:"flex",alignItems:"stretch",gap:10,height:"100%"}}>
              {/** 基础信息 */}
              <div style={{width:"33%",height:"100%",overflowY:"auto"}}>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:15}}>
                  <b>{formatMessage({id: 'pages.workOrder.processing.detail.basicInfo'})}</b>
                  <Button disabled={readonly} onClick={this.baseFormEditTrue}>
                    {formatMessage({id: 'pages.workOrder.processing.detail.button.edit'})}
                  </Button>
                </div>
                <WorkOrderInfo detail={detail} onRef={ref => this.WorkOrderInfo = ref} updateInfo={this.updateInfo} doDealtwithTime={this.doDealtwithTime} />
              </div>

              <div style={{width:1,minHeight:'100%',background:"#efefef"}}></div>

              {/** 操作部分 */}
              <div style={{width:"33%",height:"100%",overflowY:"auto"}}>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:15}}>
                  <b>{formatMessage({id: 'pages.workOrder.processing.detail.operation'})}</b>
                  <div style={{ display: "flex", gap: 10 }}>
                    <Button onClick={this.showChatModal}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.chatRecord'})}
                    </Button>
                    <Button onClick={this.openModal}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.timeTracking'})}
                    </Button>
                  </div>
                </div>
                <div style={boxStyle}>
                  <div style={labelStyle}>
                    {formatMessage({id: 'pages.workOrder.processing.detail.label.addInfo'})}：
                  </div>
                  <div>
                    <Button style={{marginRight:10}} disabled={readonly} onClick={() => this.openExtraModal(0)}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.transferProduct'})}
                    </Button>
                    <Button style={{marginRight:10}} disabled={readonly} onClick={() => this.openExtraModal(1)}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.transferDev'})}
                    </Button>
                    <Button style={{marginRight:10}} disabled={readonly} onClick={() => this.openExtraModal(2)}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.linkProject'})}
                    </Button>
                  </div>
                </div>
                <div style={boxStyle}>
                  <div style={labelStyle}>
                    {formatMessage({id: 'pages.workOrder.processing.detail.label.processOrder'})}：
                  </div>
                  <div>
                    <Button style={{marginRight:10}} disabled={allocatedDisabled || readonly} onClick={this.openAllocateModal}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.reassign'})}
                    </Button>
                    {/*<Button type="primary" disabled={readonly} onClick={() => this.doDealtwithTime('close',{})}>关闭工单</Button>*/}
                    <Button type="primary" disabled={true} onClick={() => this.doDealtwithTime('close',{})}>
                      {formatMessage({id: 'pages.workOrder.processing.detail.button.closeOrder'})}
                    </Button>
                  </div>
                </div>
                {
                  !replayDisabled && !readonly ? <ReplayModal onRef={ref => this.ReplayModal = ref} replayOk={this.operationCallback} detail={detail} /> : ''
                }
                
              </div>

              <div style={{width:1,minHeight:'100%',background:"#efefef"}}></div>

              {/** 流程部分 */}
              <div style={{width:"33%",height:"100%",overflowY:"auto",flexShrink:"0",borderRadius:4,padding:"0px 10px 0px 90px"}}>
                <TimeLineRecords orderProcessList={orderProcessList} />
              </div>
            </div>
          ) : ''
        }

        <AllocateModal onRef={ref => this.AllocateModal = ref} allocateOk={this.operationCallback} />
        <DealtwithTime onRef={ref => this.DealtwithTime = ref} getSolutionDuration={this.getSolutionDuration} />
        <ExtraFields onRef={ref => this.ExtraFields = ref} updateInfo={this.updateInfo} />
        <TimeList onRef={ref => this.TimeList = ref} />
        <div>
          <Modal
              title={formatMessage({id: 'pages.workOrder.processing.detail.modal.chatRecord.title'})}
              centered={true}
              footer={null}
              width={1000}
              visible={this.state.chatModelVisible}
              onCancel={this.handleChatModelCancel}
              maskClosable={true}

          >
            <div style={{ maxWidth: '100%', height: 500,  overflow: 'auto' }}>
              <List
                  itemLayout="horizontal"
                  dataSource={this.state.ticketChatHistoryDetail}
                  renderItem={item => (
                      <List.Item>
                        <List.Item.Meta
                            avatar={<Avatar src="/robotConfigImg/user.png" />}
                            title={<b>{item.question}</b>}
                            description={
                          <div style={{ maxWidth: '100%' }}>
                            <ReactMarkdown components={{
                              img: (props) => <img {...props} style={{ maxWidth: '100%', height: 'auto' }} />
                            }}>{item.answer}
                            </ReactMarkdown>
                          </div>
                        }
                        />
                      </List.Item>
                  )}
              />
            </div>

          </Modal>
        </div>

      </Drawer>
    )
  }
}

export default ProcessingDetail